import { defineStore } from 'pinia'
import { ref } from 'vue'

interface LoginResponse {
  username: string
  id: number
  avatarUrl: string
  token: string
  refreshToken: string | null
}

export const useTokenStore = defineStore('token', () => {
  // 存储 token 和 refreshToken
  const token = ref<string | null>(null)
  const refreshToken = ref<string | null>(null)
  const userInfo = ref<{ username: string; id: number; avatar: string } | null>(null)

  // 设置 token（完整登录响应）
  const setAuthData = (data: LoginResponse) => {
    token.value = data.token
    refreshToken.value = data.refreshToken
    userInfo.value = { username: data.username, id: data.id, avatar: data.avatarUrl }

    // 持久化存储（可选）
    sessionStorage.setItem('token', data.token)
    if (data.refreshToken) {
      sessionStorage.setItem('refreshToken', data.refreshToken)
    }
    sessionStorage.setItem(
      'userInfo',
      JSON.stringify({ username: data.username, id: data.id, avatar: data.avatarUrl }),
    )
  }

  // 获取 token
  const getToken = (): string | null => {
    return token.value || sessionStorage.getItem('token')
  }

  // 获取 refreshToken
  const getRefreshToken = (): string | null => {
    return refreshToken.value || sessionStorage.getItem('refreshToken')
  }

  // 获取用户信息
  const getUserInfo = () => {
    if (userInfo.value) return userInfo.value
    const stored = sessionStorage.getItem('userInfo')
    return stored ? JSON.parse(stored) : null
  }

  // 清除所有认证数据
  const clearAuthData = () => {
    token.value = null
    refreshToken.value = null
    userInfo.value = null
    sessionStorage.removeItem('token')
    sessionStorage.removeItem('refreshToken')
    sessionStorage.removeItem('userInfo')
  }

  return {
    token,
    refreshToken,
    userInfo,
    setAuthData,
    getToken,
    getRefreshToken,
    getUserInfo,
    clearAuthData,
  }
})
